package servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import dao.UserDao;
import entity.User;

@WebServlet("/addUser")
@MultipartConfig
public class AddUserServlet extends HttpServlet {

    private static final long serialVersionUID = 2L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String account = request.getParameter("addAccount");
        String pwd = request.getParameter("addPwd");
        String surePwd = request.getParameter("sureAddPwd");
        String userName = request.getParameter("addUserName");
        Integer role = Integer.parseInt(request.getParameter("addRole"));
        UserDao dao = new UserDao();
        int retSureAccount = dao.sure_user(account);
        if(retSureAccount >= 1){
            //用户名已存在
            request.getSession().setAttribute("errorMsg", "用户名已存在");
            request.getRequestDispatcher("./userList").forward(request, response);
        }
        if(!pwd.equals(surePwd)){
            //两次密码输入不一致
            request.getSession().setAttribute("errorMsg", "两次密码输入不一致");
            request.getRequestDispatcher("./userList").forward(request, response);
        }else{
            int retInsertUser = dao.regist(account,userName,pwd,role);
            if(retInsertUser >= 1){
                request.getRequestDispatcher("./userList").forward(request, response);
            }else{
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
        }
    }
    
    public String getFileName(Part part) {
        if (part.getSize() == 0 || part.getContentType() == null) return null;
        String header = part.getHeader("Content-Disposition");//获得Content-Disposition的头信息
        int idx = header.lastIndexOf("filename=\"");//获取filename=“字符串的开始下标
        String fileName = header.substring(idx+"filename=\"".length(), header.length()-1);
        return fileName;
    }
}
